package com.huifaapp.mall.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.HtmlActivity;
import com.huifaapp.mall.activity.JDred_packetActivity;
import com.huifaapp.mall.activity.Red_PacketActivity;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.GoodsClassifyListData;
import com.huifaapp.mall.bean.JDlianjie;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.kepler.jd.Listener.LoginListener;
import com.kepler.jd.login.KeplerApiManager;
import com.kepler.jd.sdk.exception.KeplerBufferOverflowException;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by DM on 2018/1/29.
 */

public class GoodsListXRVAdapter extends XRecyclerView.Adapter<GoodsListXRVAdapter.ViewHolder> {
    private List<GoodsClassifyListData.DataBean.ListBean> listBeans = new ArrayList<>();
    private Context context;
    private int location;
    private JDlianjie jDlianjiebean;
    private String datayouhui;
    private String datalisnajie;

    public GoodsListXRVAdapter(Context context)
    {
        this.context = context;
    }

    public void setListBeans(List<GoodsClassifyListData.DataBean.ListBean> listBeans) {
        this.listBeans = listBeans;
    }

    public List<GoodsClassifyListData.DataBean.ListBean> getListBeans() {
        return listBeans;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.goods_item_layout,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        final GoodsClassifyListData.DataBean.ListBean listBean = listBeans.get(position);
        Glide.with(context).load(listBean.getMainImageUrl()).into(holder.itme_tmall_imge);
        holder.itme_tmall_text_name.setText(listBean.getGoodsName());
        holder.itme_tmall_price.setText("¥"+listBean.getPrice()+"");
        holder.itme_tmall_price.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG);
        holder. itme_tmall_discountprice.setText("降"+listBean.getCouponMoney()+"元");
        holder.itme_tmall_totalSales.setText(listBean.getTotalSales()+"");
        holder.itme_tmall_couponMoney.setText(listBean.getConPrice()+"");
        holder.re_detail_item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                location = position;
                if (listBean.getSpuPlatform().equals("yh")){
                    Intent intent=new Intent(context,Red_PacketActivity.class);
                    intent.putExtra("shopid",listBean.getId());
                    intent.putExtra("typex","yh");
                    context.startActivity(intent);
                } else {
                    if (listBean.getSpuPlatform().equals("jd")) {
                        if ("".equals(listBean.getCouponMoney()+"")) {
                            initJDputong(listBean.getId());
                            if(KeplerApiManager.getWebViewService().isKeplerLogined()){
                                try {
                                    KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                } catch (KeplerBufferOverflowException e) {
                                    e.printStackTrace();
                                }

                            }else {
                                final LoginListener mLoginListener = new LoginListener() {
                                    @Override
                                    public void authSuccess(Object token) {
                                        // TODO Auto-generated method stub
                                        Toast.makeText(context, token + "", Toast.LENGTH_SHORT).show();
                                        //                showToken();

                                        if (KeplerApiManager.getWebViewService().isKeplerLogined()) {
                                            try {
                                                KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                            } catch (KeplerBufferOverflowException e) {
                                                e.printStackTrace();
                                            }
                                        }

                                    }

                                    @Override
                                    public void authFailed(int errorCode) {
                                        // TODO Auto-generated method stub
                                        switch (errorCode) {
                                            case KeplerApiManager.KeplerApiManagerLoginErr_Init:// 初始化失败 break;
                                            case KeplerApiManager.KeplerApiManagerLoginErr_InitIng:// 初始化没有完成 break;
                                            case KeplerApiManager.KeplerApiManagerLoginErr_openH5authPageURLSettingNull://跳转url // 为null break;
                                            case KeplerApiManager.KeplerApiManagerLoginErr_getTokenErr:// 获取失败(OAuth授权之后，获取cookie过程出错) break;
                                            case KeplerApiManager.KeplerApiManagerLoginErr_User_Cancel:// 用户取消 break;
                                            case KeplerApiManager.KeplerApiManagerLoginErr_AuthErr_ActivityOpen://打开授权页面失败 break;
                                            default:
                                                break;
                                        }
//                Toast.makeText(AllOrderActivity.this, errorCode + ":authFailed", Toast.LENGTH_SHORT).show();
                                        Log.e("jdSHOUQUAN", errorCode + ":authFailed");
                                    }
                                };
                                KeplerApiManager.getWebViewService().login((Activity) context, mLoginListener);
                            }
//                            Intent intent = new Intent(context, HtmlActivity.class);
//                            intent.putExtra("data", datalisnajie);
//                            intent.putExtra("shopid", listBean.getId());
//                            context.startActivity(intent);
                        }
                        if (""!=listBean.getCouponMoney()+""){
                            if (listBean.getCouponMoney()==0.0){
                                Map<String,String> map=new HashMap<>();
                                map.put("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
                                map.put("spuId",listBean.getId());
                                map.put("appid", AUniqueIdentifier.getDeviceId(context));
                                Log.e("优惠二和一链接接口", ApiManager.BASE_NIUPAI_URL+"jd/getConUrl"+"?token="+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&spuId="+listBean.getId()+"&appid="+AUniqueIdentifier.getDeviceId(context));
                                OkHttpUtils.post().params(map).url(ApiManager.BASE_NIUPAI_URL+"jd/getConUrl").build().execute(new StringCallback() {


                                    @Override
                                    public void onError(com.squareup.okhttp.Request request, Exception e) {

                                    }

                                    @Override
                                    public void onResponse(String response) {
                                        Log.e("优惠二和一数据",response);
                                        Gson gson=new Gson();
                                        jDlianjiebean = gson.fromJson(response, JDlianjie.class);
                                        datayouhui = jDlianjiebean.getData();
                                        if (jDlianjiebean.getCode().equals("10000")) {
                                            Intent intent=new Intent(context,JDred_packetActivity.class);
                                            intent.putExtra("shopid",listBean.getId());
                                            context.startActivity(intent);
                                        }
                                    }
                                });

                            }else {
                                Map<String,String>map=new HashMap<>();
                                map.put("token",SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
                                map.put("spuId",listBean.getId());
                                map.put("appid", AUniqueIdentifier.getDeviceId(context));

                                OkHttpUtils.post().params(map).url(ApiManager.BASE_NIUPAI_URL+"jd/getConUrl").build().execute(new StringCallback() {


                                    @Override
                                    public void onError(com.squareup.okhttp.Request request, Exception e) {

                                    }

                                    @Override
                                    public void onResponse(String response) {
                                        Log.e("优惠二和一数据zz",response);
                                        Gson gson=new Gson();
                                        jDlianjiebean = gson.fromJson(response, JDlianjie.class);
                                        datayouhui = jDlianjiebean.getData();
                                        if (jDlianjiebean.getCode().equals("10000")) {
                                            if (jDlianjiebean.getData()!=null){
//                                                Intent intent = new Intent(context, HtmlActivity.class);
//                                                intent.putExtra("shopid", listBean.getId());
//                                                intent.putExtra("data", jDlianjiebean.getData());
//                                                context.startActivity(intent);
                                                if(KeplerApiManager.getWebViewService().isKeplerLogined()){
                                                    try {
                                                        KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                                    } catch (KeplerBufferOverflowException e) {
                                                        e.printStackTrace();
                                                    }

                                                }else {
                                                    final LoginListener mLoginListener = new LoginListener() {
                                                        @Override
                                                        public void authSuccess(Object token) {
                                                            // TODO Auto-generated method stub
                                                            Toast.makeText(context, token + "", Toast.LENGTH_SHORT).show();
                                                            //                showToken();

                                                            if (KeplerApiManager.getWebViewService().isKeplerLogined()) {
                                                                try {
                                                                    KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                                                } catch (KeplerBufferOverflowException e) {
                                                                    e.printStackTrace();
                                                                }
                                                            }

                                                        }

                                                        @Override
                                                        public void authFailed(int errorCode) {
                                                            // TODO Auto-generated method stub
                                                            switch (errorCode) {
                                                                case KeplerApiManager.KeplerApiManagerLoginErr_Init:// 初始化失败 break;
                                                                case KeplerApiManager.KeplerApiManagerLoginErr_InitIng:// 初始化没有完成 break;
                                                                case KeplerApiManager.KeplerApiManagerLoginErr_openH5authPageURLSettingNull://跳转url // 为null break;
                                                                case KeplerApiManager.KeplerApiManagerLoginErr_getTokenErr:// 获取失败(OAuth授权之后，获取cookie过程出错) break;
                                                                case KeplerApiManager.KeplerApiManagerLoginErr_User_Cancel:// 用户取消 break;
                                                                case KeplerApiManager.KeplerApiManagerLoginErr_AuthErr_ActivityOpen://打开授权页面失败 break;
                                                                default:
                                                                    break;
                                                            }
//                Toast.makeText(AllOrderActivity.this, errorCode + ":authFailed", Toast.LENGTH_SHORT).show();
                                                            Log.e("jdSHOUQUAN", errorCode + ":authFailed");
                                                        }
                                                    };
                                                    KeplerApiManager.getWebViewService().login((Activity) context, mLoginListener);
                                                }
                                            }
                                        }
                                    }
                                });


                            }
                        }


                    }
                }

            }
        });
    }
    //普通二和一链接0
    private void initJDputong(String id){
        Map<String,String>map=new HashMap<String, String>();
        map.put("spuId",id);
        map.put("appid", AUniqueIdentifier.getDeviceId(context));
        map.put("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
        Log.e("京东二合一转链",ApiManager.BASE_NIUPAI_URL+"jd/getUrl"+"?spuId="+id+"&appId="+AUniqueIdentifier.getDeviceId(context)+"&token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
        OkHttpUtils.post().params(map).url(ApiManager.BASE_NIUPAI_URL+"jd/getUrl").build().execute(new StringCallback() {

            @Override
            public void onError(com.squareup.okhttp.Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                Log.e("fgdgfe",response);
                Gson gson=new Gson();
                JDlianjie jDlianjie = gson.fromJson(response, JDlianjie.class);
                datalisnajie = jDlianjie.getData();
                Log.e("kfjsdkghdfk", datalisnajie);

            }
        });

    }
    @Override
    public int getItemCount() {
        return listBeans != null?listBeans.size():0;
    }

    public class ViewHolder extends XRecyclerView.ViewHolder{
        private final ImageView itme_tmall_imge;
        private final TextView itme_tmall_text_name;
        private final TextView itme_tmall_price;
        private TextView itme_tmall_discountprice;
        private final TextView itme_tmall_totalSales;
        private final TextView itme_tmall_couponMoney;
        RelativeLayout re_detail_item;
        public ViewHolder(View itemView) {
            super(itemView);
            itme_tmall_imge = (ImageView) itemView.findViewById(R.id.itme_tmall_imge);
            itme_tmall_text_name = (TextView) itemView.findViewById(R.id.itme_tmall_text_name);
            itme_tmall_price = (TextView) itemView.findViewById(R.id.itme_tmall_price);
            itme_tmall_discountprice = (TextView) itemView.findViewById(R.id.itme_tmall_discountprice);
            itme_tmall_totalSales = (TextView) itemView.findViewById(R.id.itme_tmall_totalSales);
            itme_tmall_couponMoney = (TextView) itemView.findViewById(R.id.itme_tmall_couponMoney);
            re_detail_item= (RelativeLayout) itemView.findViewById(R.id.re_detail_item);
        }
    }
}
